// pages/index/doorService/index.js

import {AppointOrderInterface} from "../../../../utils/request.js"
import {formatTime} from "../../../../utils/util.js"

const requests = "../../../../utils/request.js"
const app = getApp()


Page({

  /**
   * 页面的初始数据
   */
  data: {
    //地址
    address:{},
    hasAddress: false,
    addressIcon:'/imgs/myaddress.png',

    //货物
    goods:[],
    hasgoods:false,
    //总重
    totalWeight:0,
    showAdd:false,
    //预计可获得积分
    integration:0,
    picker:1,
    hideFlag:false,//底部导航栏 true-隐藏  false-显示
    optionList:['所有','选项1','选项2'],
    value:'所有',
    animationData: {},//

    // goodsType1:["纸类","塑料","玻璃"],
    // goodsType2:["金属","纺织","木材"],
    typevalue1:0,
    typevalue2:0,

    typeoption1:[
    { text: '可回收物', value: 0 },
    { text: '有害垃圾', value: 1 },
    { text: '厨余垃圾', value: 2 },
    { text: '其他垃圾', value: 3 },
  ],
    typeoption2:[
        [
          { text: '纸类', value: 0,bonus: 20},
          { text: '塑料', value: 1,bonus: 30},
          { text: '金属', value: 2,bonus: 50},
          { text: '玻璃', value: 3,bonus: 40},
          { text: '织物', value: 4,bonus: 30},
        ],
        [
          { text: '灯管', value: 0,bonus: 50},
          { text: '家用化学品', value: 1,bonus: 20},
          { text: '电池', value: 2,bonus: 100},
        ],
        [
          { text: '家庭厨余垃圾', value: 0,bonus: 10},
          { text: '餐厨垃圾', value: 1,bonus: 10},
          { text: '其他厨余垃圾', value: 2,bonus: 10},
        ],
        [
          { text: '其他垃圾', value: 0, bonus:10},
        ],
      ],


    goodsTypeChoosed:"纸类",
    goodsWeight:["0.5-1kg","1-1.5kg","1.5kg以上"],
    goodsWeightChoosed:"",
    currentPrice:"--",

    //预约时间
    scheduledDate:"选择预约上门时间",
    scheduledDateChoosed:false,

    show: false,
    //留言
    note:"",
    //寄件人姓名
    senderName:"",
    //寄件人电话
    // senderPhone:"",
    urgent:false,

    //预约时间所需数据
  calendar:[],
   width:0,
   currentDayIndex:0,
   currentDay:"今天",
   currentTimeindex: 0,
   currentTime:"9:00-10:00",
   timeArr: [
       { "time": "9:00-10:00", "status": "空闲" }, 
       { "time": "10:00-11:00", "status": "空闲" }, 
       { "time": "11:00-12:00", "status": "空闲" }, 
       { "time": "14:00-15:00", "status": "空闲" }, 
       { "time": "15:00-16:00", "status": "空闲" }, 
       { "time": "16:00-17:00", "status": "空闲" }, 
       { "time": "17:00-18:00", "status": "空闲" },
       { "time": "18:00-19:00", "status": "空闲" }
       ]  
  },
  changeMenu1(value)
  {
    // console.log('onchange')
    console.log(value)
    this.setData({
      typevalue1:value.detail,
      typevalue2:0,
      goodsTypeChoosed:this.data.typeoption2[value.detail][0].text
    })
  },
  changeMenu2(value)
  {
    // console.log(value)
    this.setData({
      typevalue2:value.detail
    })
    this.chooseType(this.data.typeoption2[this.data.typevalue1][this.data.typevalue2].text)
  },
  submitOrder()
  {
    if(!app.globalData.openid)
    {
      wx.showToast({
        title: '请先登录',//提示文字
        duration:2000,//显示时长
        mask:true,//是否显示透明蒙层，防止触摸穿透，默认：false  
        icon:'error', //图标，支持"success"、"loading"  
      })
    }
    else if(!this.data.hasAddress)
    {
      wx.showToast({
        title: '请选择地址',//提示文字
        duration:2000,//显示时长
        mask:true,//是否显示透明蒙层，防止触摸穿透，默认：false  
        icon:'error', //图标，支持"success"、"loading"  
      })
    }
    else if(!this.data.hasgoods)
    {
      wx.showToast({
        title: '请添加货物',//提示文字
        duration:2000,//显示时长
        mask:true,//是否显示透明蒙层，防止触摸穿透，默认：false  
        icon:'error', //图标，支持"success"、"loading"  
      })
    }
    else if(!this.data.scheduledDateChoosed)
    {
      wx.showToast({
        title: '请选择时间',//提示文字
        duration:2000,//显示时长
        mask:true,//是否显示透明蒙层，防止触摸穿透，默认：false  
        icon:'error', //图标，支持"success"、"loading"  
      })
    }
    else{
      let that = this
      wx.showToast({
        title: '提交成功',//提示文字
        duration:2000,//显示时长
        mask:true,//是否显示透明蒙层，防止触摸穿透，默认：false  
        icon:'success', //图标，支持"success"、"loading"  
        success:async function(){ 
          // const good = {
          //   "goodsType":this.data.goodsTypeChoosed,
          //   "goodsWeight":this.data.goodsWeightChoosed,
          //   "goodsPrice":goodsPrice
          // }
          let goodsStr = ""
          // console.log(that.data.goods)
          that.data.goods.map((item)=>{
            // console.log(JSON.stringify(item)+"")
            goodsStr= goodsStr+ "goodsType:"+item.goodsType+","+"goodsWeight:"+item.goodsWeight+";"
          })
          // console.log(goodsStr)
          let dateArr = that.data.scheduledDate.split(/-|:|\s/)
          const startTime = formatTime(new Date(dateArr[0],parseInt(dateArr[1])-1,dateArr[2],dateArr[3]))
          const endTime =  formatTime(new Date(dateArr[0],parseInt(dateArr[1])-1,dateArr[2],dateArr[5]))
          let res = await AppointOrderInterface("测试地区编号",undefined,undefined,that.data.integration,1,goodsStr,undefined,0,that.data.address.address,startTime,endTime,app.globalData.userInfo.nickName,that.data.note,that.data.address.telphone,that.data.urgent?1:0,that.data.totalWeight,formatTime(new Date()),app.globalData.openid,'add')
          setTimeout(function(){
            wx.navigateTo({
              url: `../success/index?integration=${that.data.integration}`,
            })},2000
          )
          // console.log(res)
        },
        fail: function () { },   
        complete: function () { } 
     })
    }
  },
  selectDay(e)
  {
    console.log(e)
    const currentDayIndex = e.currentTarget.dataset.index
    const currentDay = e.currentTarget.dataset.date
    this.setData({
      currentDayIndex,
      currentDay
    })

  },
  selectTime(e)
  {
    console.log(e)
    const currentTimeindex = e.currentTarget.dataset.tindex
    const currentTime = e.currentTarget.dataset.time
    const scheduledDate = this.data.currentDay +" "+ currentTime
    this.setData({currentTime,
    scheduledDate,
    scheduledDateChoosed:true
    })
    this.onClose();
  },
  onLoad: function (options) {
    var that=this;
    function getThisMonthDays(year, month) {
     return new Date(year, month, 0).getDate();
    }
   // 计算每月第一天是星期几
    function getFirstDayOfWeek(year, month) {
     return new Date(Date.UTC(year, month - 1, 1)).getDay();
    }
    const date = new Date();
    const cur_year = date.getFullYear();
    const cur_month = date.getMonth() + 1;
    const cur_date=date.getDate();
    const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
    //利用构造函数创建对象
    function calendar(date,week){
     this.date=cur_year+'-'+cur_month+'-'+date;
     if(date==cur_date){
      this.week = "今天";
     }else if(date==cur_date+1){
      this.week = "明天";
     }else{
      this.week = '星期' + week;
     }
    }
    //当前月份的天数
    var monthLength= getThisMonthDays(cur_year, cur_month)
    //当前月份的第一天是星期几
    var week = getFirstDayOfWeek(cur_year, cur_month)
    var x = week;
    for(var i=1;i<=monthLength;i++){
     //当循环完一周后，初始化再次循环
     if(x>6){
      x=0;
     }
     //利用构造函数创建对象
     that.data.calendar[i] = new calendar(i, [weeks_ch[x]][0])
     x++;
    }
    //限制要渲染的日历数据天数为7天以内（用户体验）
    var flag = that.data.calendar.splice(cur_date, that.data.calendar.length - cur_date <= 7 ? that.data.calendar.length:7)
    that.setData({
     calendar: flag,
     currentDay:flag[0].date
    })
    //设置scroll-view的子容器的宽度
    that.setData({
     width: 186 * parseInt(that.data.calendar.length - cur_date <= 7 ? that.data.calendar.length : 7)
    })
   },

   urgentChange({ detail }) {
    const urgentNow = this.data.urgent
    wx.showModal({
      title: '提示',
      content: urgentNow?'取消加急处理':'确认要加急处理吗',
      success: (res) => {
        if (res.confirm) {
          this.setData({ urgent: detail });
        }
      },
    });
  },
  bindNoteInput(e)
  {
    const note = e.detail.value
    this.setData({
      note
    })
    console.log(this.data.note)
  },
  bindNameInput(e)
  {
    const senderName = e.detail.value
    this.setData({
      senderName
    })
  },
  // bindPhoneInput(e)
  // {
  //   const senderPhone = e.detail.value
  //   this.setData({
  //     senderPhone
  //   })
  // },
  showPopup() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    this.getAddressinStorage();
  },
/**
   * 获取内存中的地址缓存
   */
  getAddressinStorage()
  {
    const self = this;
    wx.getStorage({
      key:'address',
      success(res) {
        console.log("获取地址")
        console.log(res.data)
        self.setData({
          address: res.data,
          hasAddress: true
        })
      }
    })
  },
  showModal() {
    this.setData({ hideFlag: true });
  },

  hideModal() {
    this.setData({ hideFlag: false });
  },
  /**
   * 显示遮罩层
   */
  // showModal()
  // {
  //   var that = this;
  //   that.setData({
  //     hideFlag: false
  //   })
  //   // 创建动画实例
  //   var animation = wx.createAnimation({
  //     duration: 400,//动画的持续时间
  //     timingFunction: 'ease',//动画的效果 默认值是linear->匀速，ease->动画以低速开始，然后加快，在结束前变慢
  //   })
  //   this.animation = animation; //将animation变量赋值给当前动画
  //   var time1 = setTimeout(function () {
  //     that.slideIn();//调用动画--滑入
  //     clearTimeout(time1);
  //     time1 = null;
  //   }, 100)
  // },

    //动画 -- 滑入
    slideIn: function () {
      this.animation.translateY(0).step() // 在y轴偏移，然后用step()完成一个动画
      this.setData({
        //动画实例的export方法导出动画数据传递给组件的animation属性
        animationData: this.animation.export()
      })
    },

    /**
   * 隐藏底部导航
   */
  // hideModal()
  // {
  //   var that = this;
  //   var animation = wx.createAnimation({
  //     duration:400,//动画的持续时间 默认400ms
  //     timingFunction:'ease'//动画的效果 默认值是linear
  //   })
  //   this.animation = animation
  //   that.slideDown();//调用动画--滑出
  //   var time1 = setTimeout(function () {
  //     that.setData({
  //       hideFlag: true
  //     })
  //     clearTimeout(time1);
  //     time1 = null;
  //   }, 220)//先执行下滑动画，再隐藏模块
  // },

    //动画 -- 滑出
    slideDown: function () {
      this.animation.translateY(300).step()
      this.setData({
        animationData: this.animation.export(),
      })
    },
  // 点击选项
  getOption:function(e){
    var that = this;
    that.setData({
      value:e.currentTarget.dataset.value,
      hideFlag: true
    })
  },
  //取消
  mCancel: function () {
    var that = this;
    that.hideModal();
  },

  chooseType(e)
  {
    // const goodsTypeChoosed =  e.currentTarget.dataset.type
    const goodsTypeChoosed =  e
    console.log(goodsTypeChoosed)
    this.setData(
      {
        goodsTypeChoosed
      }
    )
    let per500g
    switch(goodsTypeChoosed)
    {
      case "纸类":
        per500g=5
        break;
      case "塑料":
        per500g=10
        break;
      case "金属":
        per500g=20
        break;
      case "玻璃":
        per500g=15
        break;
      case "织物":
        per500g=10
        break;
      case "灯管":
        per500g=15
        break;
      case "家用化学品":
        per500g=20
        break;
      case "电池":
        per500g=20
        break;
      case "家庭厨余垃圾":
        per500g=10
        break;
      case "餐厨垃圾":
        per500g=10
        break;
      case "其他厨余垃圾":
        per500g=10
        break;
      case "其他垃圾":
        per500g=10
        break;
    }
    let currentPrice 
    if(this.data.goodsWeightChoosed!="")
    {
      //"0.5-1kg","1-1.5kg","1.5kg以上"
      //    goodsType1:["纸类","塑料","玻璃"],
      // goodsType2:["金属","纺织","木材"],
      switch(this.data.goodsWeightChoosed)
      {
        case "0.5-1kg":
          currentPrice = per500g
          break
        case "1-1.5kg":
          currentPrice = per500g*2
          break
        case "1.5kg以上":
          currentPrice = per500g*3
          break
      }
      this.setData({
        currentPrice
      })
    }
  },

  chooseWeight(e)
  {
          //"0.5-1kg","1-1.5kg","1.5kg以上"
    const goodsWeightChoosed = e.currentTarget.dataset.weight
    this.setData({
      goodsWeightChoosed
    })
    const goodsTypeChoosed=this.data.goodsTypeChoosed
    if(goodsTypeChoosed!="")
    {
      let per500g
      switch(goodsTypeChoosed)
      {
        case "纸类":
          per500g=5
          break;
        case "塑料":
          per500g=10
          break;
        case "金属":
          per500g=20
          break;
        case "玻璃":
          per500g=15
          break;
        case "织物":
          per500g=10
          break;
        case "灯管":
          per500g=15
          break;
        case "家用化学品":
          per500g=20
          break;
        case "电池":
          per500g=20
          break;
        case "家庭厨余垃圾":
          per500g=10
          break;
        case "餐厨垃圾":
          per500g=10
          break;
        case "其他厨余垃圾":
          per500g=10
          break;
        case "其他垃圾":
          per500g=10
          break;
      }
      let currentPrice
      switch(goodsWeightChoosed){
        case "0.5-1kg":
          currentPrice=per500g
          break;
        case "1-1.5kg":
          currentPrice=per500g*2
          break;
          case "1.5kg以上":
            currentPrice=per500g*3
            break; 
      }
      this.setData({
        currentPrice
      })
    }
  },
  addList()
  {
    const goodsTypeChoosed= this.data.goodsTypeChoosed
    const goodsWeightChoosed = this.data.goodsWeightChoosed
    const goodsPrice  =this.data.currentPrice
    const curWeight = this.data.totalWeight
    let totalWeight
    switch(goodsWeightChoosed)
    {
      case "0.5-1kg":
        totalWeight=curWeight+0.5
        break
      case "1-1.5kg":
        totalWeight=curWeight+1
        break
      case "1.5kg以上":
        totalWeight=curWeight+2
        break
    }

    if(goodsWeightChoosed!==""&&goodsTypeChoosed!="")
    {
      this.hideModal()
      const good = {
        "goodsType":this.data.goodsTypeChoosed,
        "goodsWeight":this.data.goodsWeightChoosed,
        "goodsPrice":goodsPrice
      }
      let goods = this.data.goods
      let alreadyHad = false
      goods.map((item)=>{
        if(item.goodsType == goodsTypeChoosed)
          {
            item.goodsWeight = goodsWeightChoosed;
            alreadyHad=true
          }
      })
      if(!alreadyHad){
        goods.push(good)
      }
      let integration = this.data.integration
      integration+=goodsPrice
      this.setData({
        goodsTypeChoosed:"",
        goodsWeightChoosed:"",
        currentPrice:"--",
        hasgoods:true,
        goods,
        totalWeight:totalWeight,
        integration
      })
      // console.log(this.data.goods[0])
    }
  },
  deleteGood(e)
  {
    console.log(e.target.dataset)
    const index = e.target.dataset.index
    const goods = this.data.goods
    goods.splice(index,1)
    this.setData({
      goods
    })
    console.log(this.data.goods)
    if(this.data.goods.length===0)
    {
      this.setData({
        hasgoods:false
      })
    }
  },
  closeDialog()
  {
    this.hideModal()
    this.setData({
      goodsTypeChoosed:"",
      goodsWeightChoosed:"",
      currentPrice:"--"
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})